import { reqCartList, reqDeleteCartById, reqCheckCart } from "@/api";
const state = {
    cartInfo: []
}
const mutations = {
    CARTLIST(state, cartInfo) {
        state.cartInfo = cartInfo
    }
}
const actions = {
    async cartList({ commit }) {
        let result = await reqCartList()
        if (result.code == 200) {
            commit("CARTLIST", result.data)
        }
    },
    async deleteCartById({ commit }, skuId) {
        let result = await reqDeleteCartById(skuId)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    async checkCart({ commit }, { skuId, isChecked }) {
        let result = await reqCheckCart(skuId, isChecked)
        if (result.code == 200) {
            return "ok"
        } else {
            return Promise.reject(new Error("fail"))
        }
    },
    deleteCartByChecked({ getters, dispatch }) {
        let arr = []
        getters.cartInfoList.forEach(item => {
            if (item.isChecked == 1) {
                let promise = dispatch("deleteCartById", item.skuId)
                arr.push(promise)
            }
        });
        return Promise.all(arr)
    },
    handleAllChecked({ getters, dispatch }, isChecked) {
        let arr = []
        getters.cartInfoList.forEach(item => {
            let promise = dispatch("checkCart", {
                skuId: item.skuId,
                isChecked: isChecked
            })
            arr.push(promise)
        })
        return Promise.all(arr)
    }
}
const getters = {
    cartInfoList(state) {
        return state.cartInfo[0].cartInfoList || []
    }
}

export default {
    state,
    mutations,
    actions,
    getters
}